/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.posplus.losspreventiondataimporter;

import com.posplus.lossprevention.APDAOFactory;
import com.posplus.lossprevention.APDAOFactoryHibernate;
import com.posplus.strack.HistDAOFactory;
import com.posplus.strack.HistDAOFactoryHibernate;
import com.posplus.strack.POSDAOFactory;
import com.posplus.strack.POSDAOFactoryHibernate;
import com.posplus.strack.TransDAOFactory;
import com.posplus.strack.TransDAOFactoryHibernate;
import java.util.Calendar;
import com.posplus.losspreventiondataimporter.importer.DepartmentsImporter;
import com.posplus.losspreventiondataimporter.importer.EmployeesImporter;
import com.posplus.losspreventiondataimporter.importer.LaneInfoImporter;
import com.posplus.losspreventiondataimporter.importer.ProductsImporter;
import com.posplus.losspreventiondataimporter.importer.RegisterHeaderImporter;
import com.posplus.losspreventiondataimporter.importer.RegisterTransImporter;
import com.posplus.losspreventiondataimporter.service.DepartmentService;
import com.posplus.losspreventiondataimporter.service.EmployeeService;
import com.posplus.losspreventiondataimporter.service.LaneInfoService;
import com.posplus.losspreventiondataimporter.service.ProductService;
import com.posplus.losspreventiondataimporter.service.RegisterHeaderService;
import com.posplus.losspreventiondataimporter.service.RegisterTransService;
import com.posplus.losspreventiondataimporter.util.Arguments;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author ScottW
 */
public class LossPreventionDataImporter {
    
    private static Logger logger = Logger.getLogger(LossPreventionDataImporter.class);
    private String[] storeList;
    private Arguments arguments;
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        LossPreventionDataImporter lossPreventionDataImporter = new LossPreventionDataImporter(args);
        lossPreventionDataImporter.importData();
    }
    
    public LossPreventionDataImporter(String[] args){  
        
        logger.debug("Processing arguments");
        arguments = new Arguments(args);     
        
        String loggerConfig;
        if(arguments.getLogConfig() != null)
            loggerConfig = arguments.getLogConfig();
        else
            loggerConfig = "log4j.properties";
        
	try{
	    PropertyConfigurator.configure(loggerConfig);
	    logger.debug("Loading log configfile from: " + loggerConfig);
	}catch(Exception e){
	    logger.debug("Unable to load config file " + loggerConfig, e);
	}    
	
        logger.debug("Loading store config from: " + arguments.getConfigFile());
        
        logger.debug("Loading configuration");
        Properties properties = new Properties();    
        try{
            String configFile;
            if(arguments.getConfigFile() == null){
                properties.load(getClass().getClassLoader().getResourceAsStream("com/posplus/losspreventiondataimporter/config/config.properties"));
            }
            else
                properties.load(new FileInputStream(arguments.getConfigFile()));
            
            if(logger.isDebugEnabled()){
                logger.debug("stores.list=" + properties.getProperty("stores.list"));
            }
        }catch(IOException ex){
            logger.fatal(ex);
            System.exit(-1);
        }   
        
        storeList = properties.getProperty("stores.list").split(","); 
    }
    
    private void importData(){ 
        
        for(String store : storeList){
            logger.info("Importing from store " + store);
            importDataFromStore(store);
            logger.info(store + " import finished");
        }
    }
    
    private void importDataFromStore(String store){
        
        long startTime = System.currentTimeMillis();
        logger.info("### Import Begin ###");
           
        
        POSDAOFactory svtDAOFactory = 
                new POSDAOFactoryHibernate("/com/posplus/losspreventiondataimporter/config/" + store + "/pos-hibernate.cfg.xml");
        TransDAOFactory transFactory =
                new TransDAOFactoryHibernate("/com/posplus/losspreventiondataimporter/config/" + store + "/trans-hibernate.cfg.xml");
        HistDAOFactory histFactory =
                new HistDAOFactoryHibernate("/com/posplus/losspreventiondataimporter/config/" + store + "/hist-hibernate.cfg.xml");
       
        APDAOFactory lpDAOFactory = 
                new APDAOFactoryHibernate("/com/posplus/lossprevention/hibernate.cfg.xml");
        if(arguments.isImportCashiers())
            importEmployees(svtDAOFactory, lpDAOFactory, store);
        
        if(arguments.isImportDepartments())
            importDepartments(svtDAOFactory, lpDAOFactory);
        
        if(arguments.isImportProducts())
            importProducts(svtDAOFactory, lpDAOFactory);
        
        if(arguments.isImportRegisters())
            importLaneInfo(transFactory, lpDAOFactory, store);
        
        if(arguments.isImportTransactions()){
            importRegisterHeader(histFactory, lpDAOFactory, arguments.getStart(), arguments.getEnd(), store);
            importRegisterTrans(histFactory, lpDAOFactory, arguments.getStart(), arguments.getEnd(), store);
        }
        
        long endTime = System.currentTimeMillis();
        
        long timeDifference = endTime - startTime;
        
        Timespan totalRunTime = new Timespan(timeDifference);
        
        logger.info("Total Runtime: " + totalRunTime.toString());
    }
    
    
    private static void importDepartments(POSDAOFactory strackDAOFactory,
            APDAOFactory lpDAOFactory){
        
        DepartmentsImporter departmentsImport = new DepartmentsImporter(new DepartmentService(strackDAOFactory), lpDAOFactory);
        departmentsImport.dataImport();
    }
    
    private static void importProducts(POSDAOFactory svtDAOFactory, 
            APDAOFactory lpDAOFactory){
        
        ProductsImporter productImporter = new ProductsImporter(new ProductService(svtDAOFactory), lpDAOFactory);
        productImporter.dataImport();
    }
    
    private static void importEmployees(POSDAOFactory svtFactory,
                APDAOFactory lpFactory, String store){
        
        logger.info("Employees Import start");
        long employeeStart = System.currentTimeMillis();
        EmployeesImporter employeesImporter = new EmployeesImporter(new EmployeeService(svtFactory), lpFactory);
        employeesImporter.setStoreCode(store);
        employeesImporter.dataImport();
        long employeeEnd = System.currentTimeMillis();
        Timespan timespan = new Timespan(employeeEnd - employeeStart);
        logger.info("Employees Import end");
        logger.info("Duration: " + timespan.toString());
    }
    
    private static void importLaneInfo(TransDAOFactory svtFactory,
                APDAOFactory lpFactory, String store){
        
        logger.info("Lane Info Import Begin");
        long laneInfoStart = System.currentTimeMillis();
        LaneInfoImporter laneInfoImporter = new LaneInfoImporter(new LaneInfoService(svtFactory),
                lpFactory);
        laneInfoImporter.setStoreCode(store);
        laneInfoImporter.dataImport();
        long laneInfoEnd = System.currentTimeMillis();
        Timespan timespan = new Timespan(laneInfoEnd - laneInfoStart);
        logger.info("Lane Info Import End");
        logger.info("Duration: " + timespan.toString());
    }
    
    private static void importRegisterTrans(HistDAOFactory svtFactory,
            APDAOFactory lpFactory, Calendar start, Calendar end, String store){
        
        logger.info("Register Trans Import Begin");
        long registerTransStart = System.currentTimeMillis();
        RegisterTransImporter registerTransImporter = new RegisterTransImporter(new RegisterTransService(svtFactory), lpFactory);
        registerTransImporter.setStoreCode(store);
        registerTransImporter.dataImport(start, end);
        long registerTransEnd = System.currentTimeMillis();
        Timespan timespan = new Timespan(registerTransEnd - registerTransStart);
        logger.info("Register Trans Import End");
        logger.info("Duration: " + timespan.toString());
    }
    
    public static void importRegisterHeader(HistDAOFactory svtFactory,
            APDAOFactory lpFactory, Calendar start, Calendar end, String store){
        
        logger.info("Register Header Import Begin");
        long registerHeaderStart = System.currentTimeMillis();
        RegisterHeaderImporter registerHeaderImporter = new RegisterHeaderImporter(new RegisterHeaderService(svtFactory),
                lpFactory);
        registerHeaderImporter.setStoreCode(store);
        registerHeaderImporter.dataImport(start, end);
        long registerHeaderEnd = System.currentTimeMillis();
        Timespan timespan = new Timespan(registerHeaderEnd - registerHeaderStart);
        logger.info("Register Header Import End");
        logger.info("Duration: " + timespan.toString());
    }
}
